package com.hf.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hf.utils.StringUtils;

@WebFilter
public class CharSetFilter implements Filter {
	
	public String unecode = "";
	public String includeString = "";
	public String encode = "utf-8";
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse reps, FilterChain arg2)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) reps;
		
		req.setCharacterEncoding(encode);
		reps.setContentType("text/html;charset=utf-8");
		reps.setCharacterEncoding(encode);
		
		HttpSession session = request.getSession();
		
		String url = request.getRequestURI().toString();
		String[] urls = includeString.split(",");
		
		if(StringUtils.isExitsUrl(url,urls)){
			arg2.doFilter(req,reps);
		}else{
			if(session.getAttribute("user_id")==null){
				response.sendRedirect("login.jsp");
			}else{
				arg2.doFilter(req,reps);
			}
		}


	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		unecode = arg0.getInitParameter("unecode");
		includeString = arg0.getInitParameter("includeString");
	}

}
